<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{Coupon, UserCoupon};
use think\facade\{Db, Log};
use think\Request;

class CouponController extends BaseController
{
    /**
     * 获取优惠券列表
     */
    public function list(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 优惠券类型筛选
            if (isset($params['coupon_type'])) {
                $where[] = ['coupon_type', '=', $params['coupon_type']];
            }
            
            // 有效期筛选
            if (!empty($params['start_time'])) {
                $where[] = ['valid_end_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['valid_start_time', '<=', $params['end_time']];
            }
            
            $list = Coupon::where($where)
                ->withCount(['users'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取优惠券列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 创建优惠券
     */
    public function create(Request $request)
    {
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            $validate = validate('Coupon');
            if (!$validate->check($params)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            
            Coupon::create([
                'merchant_id' => $merchant_id,
                'coupon_name' => $params['coupon_name'],
                'coupon_type' => $params['coupon_type'],
                'coupon_value' => $params['coupon_value'],
                'valid_start_time' => $params['valid_start_time'],
                'valid_end_time' => $params['valid_end_time'],
                'usage_rules' => $params['usage_rules']
            ]);
            
            return json(['code' => 0, 'msg' => '创建成功']);
        } catch (\Exception $e) {
            Log::error('创建优惠券失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 发放优惠券
     */
    public function issue(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $coupon = Coupon::where([
                'id' => $params['coupon_id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$coupon) {
                return json(['code' => 1, 'msg' => '优惠券不存在']);
            }
            
            // 批量发放优惠券
            $userIds = $params['user_ids'];
            $data = [];
            foreach ($userIds as $userId) {
                $data[] = [
                    'merchant_id' => $merchant_id,
                    'user_id' => $userId,
                    'coupon_id' => $coupon->id,
                    'coupon_name' => $coupon->coupon_name,
                    'coupon_value' => $coupon->coupon_value,
                    'valid_start_time' => $coupon->valid_start_time,
                    'valid_end_time' => $coupon->valid_end_time,
                    'usage_rules' => $coupon->usage_rules,
                    'status' => 0, // 未使用
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ];
            }
            
            UserCoupon::insertAll($data);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '发放成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('发放优惠券失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取优惠券发放记录
     */
    public function records(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 优惠券ID筛选
            if (!empty($params['coupon_id'])) {
                $where[] = ['coupon_id', '=', $params['coupon_id']];
            }
            
            // 使用状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            // 用户筛选
            if (!empty($params['keyword'])) {
                $where[] = ['user_id', 'in', function ($query) use ($params) {
                    $query->name('user')
                        ->where('mobile|real_name', 'like', "%{$params['keyword']}%")
                        ->field('id');
                }];
            }
            
            $list = UserCoupon::where($where)
                ->with(['user', 'coupon'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取优惠券发放记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取优惠券统计数据
     */
    public function statistics(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $coupon_id = $request->get('coupon_id');
            
            $where = [['merchant_id', '=', $merchant_id]];
            if ($coupon_id) {
                $where[] = ['coupon_id', '=', $coupon_id];
            }
            
            $stats = [
                'total_issued' => UserCoupon::where($where)->count(), // 发放总数
                'total_used' => UserCoupon::where($where)->where('status', 1)->count(), // 已使用数
                'total_expired' => UserCoupon::where($where)
                    ->where('status', 0)
                    ->where('valid_end_time', '<', date('Y-m-d H:i:s'))
                    ->count(), // 已过期数
                'total_valid' => UserCoupon::where($where)
                    ->where('status', 0)
                    ->where('valid_end_time', '>=', date('Y-m-d H:i:s'))
                    ->count() // 有效数
            ];
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $stats]);
        } catch (\Exception $e) {
            Log::error('获取优惠券统计数据失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 